package com.itxiao.filter;

import com.alibaba.fastjson.JSON;

import com.itxiao.config.RedisKeyConfig;
import com.itxiao.config.SystemConfig;
import com.itxiao.entity.SysUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@WebFilter("/api/**")
public class TokenFilter implements Filter {
    @Resource
    private StringRedisTemplate template;

    //实现令牌续期，保证令牌的空闲时间
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取令牌
        String token=((HttpServletRequest)servletRequest).getHeader(SystemConfig.HEADER_TOKEN);
        //2.验证本次是否存在令牌
        if(StringUtils.hasLength(token)){
            //3.redis 设置有效期
            String json=template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN+token);
            template.expire(RedisKeyConfig.AUTH_LOGIN_TOKEN+token,30, TimeUnit.MINUTES);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
